package com.oocl.controller;

import javax.annotation.Resource;
import javax.jws.WebParam.Mode;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.oocl.pojo.User;
import com.oocl.service.UserService;

@Controller
@RequestMapping("/")
public class UserController {
	@Resource(name="userService")
	private UserService userService;
	
	@RequestMapping(value="add",method=RequestMethod.POST)
	public String addUser(User user,Model model){
		if(null==user || "".equals(user.getUsername().trim()) || "".equals(user.getPassword().trim())){
			model.addAttribute("error", "username or password can not be empty!");
			return "register";
		}
		System.out.println(user);
		User u = userService.findUserByUsername(user.getUsername());
		if(u!=null){
			model.addAttribute("error", "username has existed!");
			return "register";
		}
		User u2 = userService.addUser(user);
		if(null==u2){
			model.addAttribute("error", "register fail!");
			return "register";
		}
		return "login";
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(String username,String password,Model model,HttpSession session){
		if(null==username || "".equals(username.trim()) || null==password || "".equals(password.trim())){
			model.addAttribute("error", "username or password can not be empty!");
			return "login";
		}
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		boolean flag = userService.checkUser(user);
		if(!flag){
			model.addAttribute("error", "username or password error!");
			return "login";
		}
		session.setAttribute("user", user);
		return "suc";
	}
}
